<template>
  <div
    :style="{
      '--theme-color': web_info.THEME_COLOR,
      '--theme-color-lighter': THEME_COLOR_LIGHTER,
      '--theme-color-darker': THEME_COLOR_DARKER
    }"
  >
    <component :is="Header" v-if="!this.$route.meta.fullScreen"></component>
    <section
      class="app-body"
      :style="{
        width: is_mobile ? '7.2rem' : 'none',
        backgroundColor: is_mobile ? '#ffffff' : '#f5f6f7'
      }"
    >
      <div class="loading-box" v-show="is_loading">
        <div class="loading-mask"></div>
        <div class="loading-ani">
          <van-loading :color="web_info.THEME_COLOR" vertical>
            <span style="color:#fff">{{
              $t("locale.layouts.default.t1")
            }}</span>
          </van-loading>
        </div>
      </div>
      <nuxt :keep-alive="this.$route.meta.keepAlive || is_mobile" />
    </section>
   <component
      :is="Footer"
      v-if="!v2BottomNav && !this.$route.meta.fullScreen"
    ></component>
   <!-- <component
      :is="V2MFooter"
      v-if="v2BottomNav && !this.$route.meta.fullScreen"
    ></component> -->
    <div class="app_download" v-show="!this.is_mobile && web_info.ANDROID_APP_URL && kl_md.KLAPP == 1">
      <Icon type="logo-android" size="34"/>
      <div class="app_qrcode">
        <div class="app_qrcode_content">
          <div class="qrcode_item_box" id="app_qrcode">
          </div>
          <p>APP下载</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import VHeader from "~/components/pc/Header";
import MHeader from "~/components/mobile/Header";
import VFooter from "~/components/pc/Footer";
import MFooter from "~/components/mobile/Footer";
import QuestionFooter from "~/components/mobile/QuestionFooter.vue";
import axios from 'axios'
export default {
  components: {
    VHeader,
    VFooter,
    MHeader,
    MFooter,
    QuestionFooter
  },
  head() {
    return {
      link: [
        { rel: "icon", type: "image/x-icon", href: this.web_info.FAVICON }
      ],
      title: this.$route.meta.title,
      meta: [
        { name: "keyword", content: this.web_info.SEO_KEY_WORDS },
        { name: "description", content: this.web_info.SEO_DESCRIPTION }
      ]
    };
  },
  data() {
    return {
      whiteList: ["MParent", "MStudySituation", "MTestLog"], //家长路由跳转白名单
      smrzWhiteList: [
        "MLogin",
        "MRegist",
        "MAuthentication",
        "MAuthDetail",
        "MAgreement",
        "MProtocol",
        "MPrivacyPolicy",
        "MParent",
        "MStudySituation",
        "MTestLog",
        "MQuickpay",
        "MIntentionScholl"
      ] //医院实名认证白名单
    };
  },
  computed: {
    ...mapState({
      is_mobile(state) {
        return state.is_mobile;
      },
      is_loading(state) {
        return state.is_loading;
      },
      web_info(state) {
        return state.web_info;
      },
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
      user_type(state) {
        return state.user_type;
      },
      is_ios(state) {
        return state.is_ios;
      },
      authentication(state) {
        return state.authentication;
      },
      kl_md(state) {
        return state.kl_md;
      },
      is_in_wechat(state) {
        return state.is_in_wechat;
      },
      is_in_minigram(state) {
        return state.is_in_minigram;
      },
      is_wechat_ios_limit(state) {
        return state.is_wechat_ios_limit;
      },
      THEME_COLOR_LIGHTER(state) {
        return state.THEME_COLOR_LIGHTER;
      },
      THEME_COLOR_DARKER(state) {
        return state.THEME_COLOR_DARKER;
      }
    }),
    is_wechat() {
      if (process.client) {
        var ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    is_minigram() {
      if (!wx.miniProgram) {
        return false;
      }
      wx.miniProgram.getEnv(res => {
        if (res.miniprogram) {
          return true;
        } else {
          return false;
        }
      });
    },
    appDownloadUrl(){
      return this.web_info.DOMAIN + '/m/app-download'
    },
    Header() {
      return this.is_mobile ? MHeader : VHeader;
    },
    Footer() {
      return this.is_mobile ? MFooter : VFooter;
    },
    V2MFooter() {
      return QuestionFooter;
    },
    v2BottomNav() {
      return this.$route.meta.v2BottomNav;
    }
  },
  watch: {
    // is_mobile(newVal, oldVal) {
    //   if (newVal !== oldVal) {
    //     this.is_show = false;
    //     this.$nextTick(() => {
    //       this.is_show = true;
    //     });
    //   }
    // }
    $route(new_val, old_val) {
      // console.log("路由发生变化", new_val, old_val);
      // console.log(window.location.href,new_val.meta.title);
      // 或者
      wx.miniProgram.getEnv(function(res) {
        // console.log(res.miniprogram) // true
        if(res.miniprogram){
          let postData = {
            path: window.location.href,
            title: new_val.meta.title,
            imageUrl:""
          };
          wx.miniProgram.postMessage({ data: {postData:JSON.stringify(postData)} });
        }
      })
      //已经登录|不在白名单内|已经认证|手机端|开启功能
      if (
        this.token &&
        Object.keys(this.user_info).length > 0 &&
        !this.smrzWhiteList.includes(new_val.name) &&
        !this.authentication.userId &&
        this.is_mobile &&
        this.kl_md.KLSMRZ == 1
      ) {
        this.$dialog
          .alert({
            message: "您尚未通过认证",
            confirmButtonText: "去认证"
          })
          .then(() => {
            this.$router.push("/m/authentication");
          });
      }
      if (
        this.token &&
        Object.keys(this.user_info).length > 0 &&
        !this.smrzWhiteList.includes(new_val.name) &&
        !this.user_info.gradeId && !this.user_info.schoolCollegeId &&
        this.is_mobile &&
        this.kl_md.KLYXRZ == 1
      ) {
        this.$dialog
          .alert({
            message: "您尚未完善信息",
            confirmButtonText: "去完善"
          })
          .then(() => {
            this.$router.push("/m/intention-school");
          });
      }
    }
  },
  methods: {
    ...mapActions([
      "initUser",
      "initMember",
      "initWebInfo",
      "initBuyRecord",
      "initBuyCourseRecord",
      "initSignAgreement",
      "initSignInCourse",
      "initMajorTree",
      "initFriendsList",
      "getWxValid",
      "initRtcInfo",
      "initAuthentication"
    ]),
    ...mapMutations(["SET_IS_MINIGRAM", "SET_IS_MOBILE"]),
    initEnv() {
      var ua = navigator.userAgent;
      wx.miniProgram.getEnv(res => {
        if (res.miniprogram) {
          //在小程序里
          this.SET_IS_MINIGRAM(true);

          //在电脑微信打开小程序处理
          const { fullPath } = this.$route;
          let safe_list = ["/binding", "/pay-result"]; //不进行设备判断跳转的路由
          if (!/\/m/i.test(fullPath)) {
            if (safe_list.includes(this.$route.path) == -1) {
              return;
            } else {
              this.SET_IS_MOBILE(true);
              this.$router.replace("/m");
            }
          }
        } else {
          //不在小程序里
          this.SET_IS_MINIGRAM(false);
        }
      });
    },
    initAppQrcode(){
      let url = window.location.origin + "/m/app-download";
      if(document.getElementById("app_qrcode")){
        let qrcode = new QRCode(document.getElementById("app_qrcode"), {
          width: 96,
          height: 96
        });
        qrcode.makeCode(url);
      }
      
    }
  },
  async created() {
    if (process.client) {
      FastClick.attach(document.body);
      this.initEnv();
      this.$store.commit("INIT_USER");
      this.$nextTick(()=>{
        this.initAppQrcode();
      })
    }
    if(this.token && Object.keys(this.user_info).length > 0){
      this.initUser();
      this.initMember();
      this.initAuthentication();
      this.initBuyRecord();
      this.initRtcInfo();
      this.initBuyCourseRecord();
      this.initSignAgreement();
      this.initSignInCourse();
    }
    this.initMajorTree();
    this.initFriendsList();
    this.getWxValid();
    await this.initWebInfo();
    if (
      this.user_type === "parent" &&
      !this.whiteList.includes(this.$route.name)
    ) {
      // console.log("我是家长");
      this.$router.replace("/m/parent");
    } else {
      // console.log("我是学生");
      let { name } = this.$route;
      // console.log("路由页面",name);
      // console.log("用户信息",this.user_info);
      //已经登录|不在白名单内|已经认证|手机端|开启功能
      if (
        this.token &&
        Object.keys(this.user_info).length > 0 &&
        !this.smrzWhiteList.includes(name) &&
        !this.authentication.userId &&
        this.is_mobile &&
        this.kl_md.KLSMRZ == 1
      ) {
        this.$dialog
          .alert({
            message: "您尚未通过认证",
            confirmButtonText: "去认证"
          })
          .then(() => {
            this.$router.push("/m/authentication");
          });
      }
    }

    if (process.client) {
      if (this.is_wechat_ios_limit && this.is_in_wechat && this.is_ios) {
        this.$dialog
          .alert({
            title: this.$t("locale.layouts.default.t2"),
            message: this.$t("locale.layouts.default.t3")
          })
          .then(() => {
            // on close
          });
      }
    }
  },
  mounted() {
    //阻止在safari上双指放大缩小页面
    if (this.is_ios) {
      this.$nextTick(() => {
        // 阻止双击放大
        window.lastTouchEnd = 0;
        document.addEventListener("touchstart", function(event) {
          if (event.touches.length > 1) {
            event.preventDefault();
          }
        });
        document.addEventListener(
          "touchend",
          function(event) {
            var now = new Date().getTime();
            if (now - lastTouchEnd <= 300) {
              event.preventDefault();
            }
            lastTouchEnd = now;
          },
          false
        );

        // 阻止双指放大
        document.addEventListener("gesturestart", function(event) {
          event.preventDefault();
        });
      });
    }
  }
};
</script>
<style lang="scss">
html {
  font-family: "Source Sans Pro", -apple-system, BlinkMacSystemFont, "Segoe UI",
    Roboto, "Helvetica Neue", Arial, sans-serif;
  font-size: 16px;
  word-spacing: 1px;
  -ms-text-size-adjust: 100%;
  -webkit-text-size-adjust: 100%;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: border-box;
  margin: 0;
}
.app_download{
    position: fixed;
    right: 16px;
    top: 50%;
    transform: translateY(-50%);
    width: 44px;
    height: 44px;
    border-radius: 50%;
    background: #fff;
    text-align: center;
    line-height: 44px;
    cursor: pointer;
    box-shadow: 0 2px 4px 0 rgba(0 ,0 ,0 , .05);
    &:hover>.app_qrcode{
      display: block;
    }
    .app_qrcode{
      position: absolute;
      width: 120px;
      height: 136px;
      padding-right: 6px;
      right: 44px;
      top: 0;
      display: none;
      box-sizing: border-box;
      z-index: 2001;
      .app_qrcode_content{
        width: 100%;
        height: 100%;
        background: #fff;
        padding-top: 8px;
        box-sizing: border-box;
        border-radius: 4px;
        box-shadow: 0 2px 4px 0 rgba(0 ,0 ,0 , .1);
        .qrcode_item_box{
          width: 96px;
          height: 96px;
          margin: 0 auto;
        }
        p{
          line-height: 30px;
          font-size: 14px;
          color: #4d4d4d;
        }
      }
      
    }
  }
.app-body {
  position: relative;
  min-height: calc(100vh - 1.6rem);
  background-color: #f5f6f7;
  
  .loading-box {
    z-index: 9999;
    position: fixed;
    top: 0;
    left: 0;
    width: 7.2rem;
    height: 100vh;
    .loading-mask {
      position: absolute;
      top: 0;
      left: 0;
      width: 7.2rem;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.7);
    }
    .loading-ani {
      position: absolute;
      top: 0;
      left: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
    }
  }
}
@supports (bottom: constant(safe-area-inset-bottom)) {
  .app-body {
    margin-bottom: constant(safe-area-inset-bottom);
  }
}
@supports (bottom: env(safe-area-inset-bottom)) {
  .app-body {
    margin-bottom: env(safe-area-inset-bottom);
  }
}
</style>
